package test2;

import java.io.*;
import java.net.*;

public class HttpServer {
    public static void main(String[] args) {
        try {
            // 创建服务器端的ServerSocket，监听端口 8080
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("服务器启动，等待客户端连接...");

            while (true) {
                // 接受客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接");

                // 获取客户端的输入流
                BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                OutputStream output = clientSocket.getOutputStream();

                // 读取客户端请求的第一行（请求方式、请求路径等信息）
                String requestLine = input.readLine();
                System.out.println("请求行: " + requestLine);

                // 解析 GET 请求的路径和参数
                String[] requestParts = requestLine.split(" ");
                if (requestParts.length > 1 && requestParts[0].equals("GET")) {
                    String requestPath = requestParts[1];

                    // 解析请求路径中的参数（如果有的话）
                    String responseMessage = "Hello, World!";
                    if (requestPath.contains("?")) {
                        String query = requestPath.split("\\?")[1];
                        String[] queryParams = query.split("&");
                        for (String param : queryParams) {
                            String[] keyValue = param.split("=");
                            if (keyValue.length == 2 && keyValue[0].equals("name")) {
                                responseMessage = "Hello, " + keyValue[1] + "!";
                                break;
                            }
                        }
                    }

                    // 构造 HTTP 响应
                    String response = "HTTP/1.1 200 OK\r\n" +
                            "Content-Type: text/plain\r\n" +
                            "Content-Length: " + responseMessage.length() + "\r\n" +
                            "\r\n" +
                            responseMessage;

                    // 发送响应
                    output.write(response.getBytes());
                }

                // 关闭连接
                input.close();
                output.close();
                clientSocket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

